package com.zyw.weibo.ui.support;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;

import com.zyw.weibo.data.Weibo;
import com.zyw.weibo.data.remote.NetEngine;
import com.zyw.weibo.data.remote.NetOperatingManager;

import cn.emagsoftware.ui.adapterview.AsyncDataExecutor;
import cn.emagsoftware.ui.adapterview.DataHolder;

public class WeiboAsyncDataExecutor extends AsyncDataExecutor {
	
	protected Context context = null;
	protected int imageMaxWidth;
	
	public WeiboAsyncDataExecutor(Context context,int imageMaxWidth){
		super(1, 1);
		this.context = context;
		this.imageMaxWidth = imageMaxWidth;
	}
	
	@Override
	public void onExecute(List<Integer> arg0, List<DataHolder> arg1, List<Integer> arg2) throws Exception {
		// TODO Auto-generated method stub
		DataHolder holder = arg1.get(0);
		Weibo wb = (Weibo)holder.getData();
		int index = arg2.get(0);
		String picUrl = null;
		boolean isHead = false;
		if(index == 0){
			String selfpicture = wb.blogsender.selfpicture;
			if(TextUtils.isEmpty(selfpicture)) {
				if(wb.image == null){
					picUrl = NetOperatingManager.URL_HOST + wb.originalblogid.image.smallimageurl;
				}else{
					picUrl = NetOperatingManager.URL_HOST + wb.image.smallimageurl;
				}
			}else{
				isHead = true;
				picUrl = NetOperatingManager.URL_HOST + selfpicture;
			}
		}else if(index == 1){
			if(wb.image == null){
				picUrl = NetOperatingManager.URL_HOST + wb.originalblogid.image.smallimageurl;
			}else{
				picUrl = NetOperatingManager.URL_HOST + wb.image.smallimageurl;
			}
		}else if(index == 2){
			picUrl = NetOperatingManager.URL_HOST + wb.originalblogid.image.smallimageurl;
		}
		byte[] data = NetEngine.requestImage(context, picUrl);
		Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
		if(bitmap != null) {
			if(!isHead){
				int imageWidth = bitmap.getWidth();
				if(imageWidth > imageMaxWidth){
					int height = bitmap.getHeight();
					int newHeight = imageMaxWidth*height/imageWidth;
					Bitmap temp = bitmap;
					bitmap = Bitmap.createScaledBitmap(bitmap,imageMaxWidth,newHeight,true);
					if(temp != null && !temp.isRecycled()){
						temp.recycle();
						temp = null;
					}
				}
			}
			holder.setAsyncData(index, new BitmapDrawable(bitmap));
		}
	}
	
}
